package com.example.miniofenpian.controller;


import cn.hutool.extra.spring.SpringUtil;
import com.example.miniofenpian.config.OssConfig;
import com.example.miniofenpian.service.FileService;
import com.example.miniofenpian.service.OSSInitService;
import com.example.miniofenpian.util.Result;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


/**
 * oss整合本地文件上传
 * <p>
 * 1. 模拟从数据库获取oss配置信息
 * 2. 根据配置信息创建oss client
 * 3. 根据配置自动上传(oss/本地)文件
 * </p>
 *
 * @since 2022-08-22 17:47:31
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private List<FileService> fileServices;

    @SneakyThrows
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        FileService fileService = fileServices.stream().filter(FileService::handel).findFirst().get();
        return Result.ok(fileService.upload(file));
    }


    @Autowired
    private OSSInitService ossInitService;

    @PutMapping("/select/{key}")
    public Result selectKey(@PathVariable String key) {
        // 根据key修改数据为启用,其他禁用

        // 数据库的数据不需要这么做
        SpringUtil.getBean(StringRedisTemplate.class).opsForValue().set("qiehuan", key);
        // 数据库的数据不需要这么做

        ossInitService.init();
        log.info("切换为：{}", key);
        return Result.ok("切换成功 变为:" + key);
    }
}
